package com.springcloud.test.controller;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Desc Eureka服务注册中心实现简单的负载均衡(不基于ribbon)
 * ----------------
 * @CLASS_NAME: DcController
 * ----------------
 * @Author jovi
 * ----------------
 * @Date 2020-03-24 15:41
 */
@RestController
public class DcController {

    /**
     * 负载均衡客户端的抽象定义
     */
    @Resource
    private LoadBalancerClient loadBalancerClient;

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer")
    public String dc() {
        ServiceInstance instance = loadBalancerClient.choose("app-server");
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/dc";
        System.out.println(url);
        return restTemplate.getForObject(url, String.class);
    }
}
